package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func Authentication() gin.HandlerFunc {
	return func(c *gin.Context) {
		var (
			rsp  = input.Gin{C: c}
			authToken  = ""
		)

		secret := viper.GetString("jwt_secret")

		headerField := c.Request.Header.Get("x-auth-token")
		queryField := c.Query("xAuthToken")

		cookieField, _ := c.Cookie("xAuthToken")

		if headerField == "" && queryField == "" && cookieField == "" {
			rsp.SendJSON(http.StatusUnauthorized, errno.UNAUTHORIZED, nil)
			c.Abort()
			return
		} else if headerField != "" {
			authToken = headerField
		} else if cookieField != "" {
			authToken = cookieField
		} else if queryField != "" {
			authToken = queryField
		}

		if _, err :=util.Parse(authToken, secret); err != nil {
			rsp.SendJSON(http.StatusInternalServerError, errno.ERROR, err)
			c.Abort()
			return
		}

		// TODO token过期处理

		c.Next()
	}
}